﻿using System;
using System.Web;
using System.Xml;
using System.Reflection;
using UComment.Spam;
using umbraco;
using umbraco.BusinessLogic;

namespace UComment
{
    public class Config
    {
        public static SpamChecker GetChecker()
        {
            SpamChecker checker = null;
             var providerAssembly = GetProviderAssembly();
            try
            {
               
                var assemblyFile =
                    HttpContext.Current.Server.MapPath(
                    String.Format("{0}/..{1}.dll",
                    GlobalSettings.Path,
                    providerAssembly));

                var checkerAssembly = Assembly.LoadFrom(assemblyFile);

                checker = (SpamChecker) Activator.CreateInstance(checkerAssembly.GetType(GetProviderType()));
            }
            catch (Exception e)
            {
               Log.Add(LogTypes.Error, User.GetUser(0), 0, 
                   string.Format("Couln't create an instance of {0} -> {1}", providerAssembly, e.Message));
            }

            return checker;
        }

        public static string GetProviderAssembly()
        {
            
            var config = new XmlDocument();
            
            config.Load(
                HttpContext.Current.Server.MapPath(umbraco.GlobalSettings.Path + "/plugins/UComment/UComment.config"));

            var key = config.SelectSingleNode("/SpamChecker");

            return key.Attributes["assembly"].Value;
 
        }

        public static string GetProviderType()
        {
            var config = new XmlDocument();
            config.Load(
                HttpContext.Current.Server.MapPath(umbraco.GlobalSettings.Path + "/plugins/UComment/UComment.config"));

            var key = config.SelectSingleNode("/SpamChecker");

            return key.Attributes["type"].Value;
        }

        public static string GetSetting(string key)
        {
            var config = new XmlDocument();
            config.Load(
                HttpContext.Current.Server.MapPath(umbraco.GlobalSettings.Path + "/plugins/UComment/UComment.config"));

            var node = 
                config.SelectSingleNode(
                string.Format("/SpamChecker/Settings/add [@key = '{0}']",key));

            return node.Attributes["value"].Value;
        }
    }
}
